package com.zxmr.util;

import java.util.concurrent.ArrayBlockingQueue;

import com.zxmr.action.Request;
import com.zxmr.action.UserTraceAddRequestPayload;
import com.zxmr.domain.account.User;
import com.zxmr.domain.component.UserActionTrace;

public class UserTraceManager {

	static Thread thread;
	static ArrayBlockingQueue<Request> queue = new ArrayBlockingQueue<Request>(100);
	public static void init()
	{
		thread = new Thread(new Runnable(){

			@Override
			public void run() {
				while(true)
				{
					try {
						Request request = queue.take();
						request.setInternal(true);
						request.send(null, "zxmr.utility");
					
					} catch(Exception e)
					{
						if(e instanceof InterruptedException)
						{
							System.out.println("interrupted");
							break;
						}
							
						e.printStackTrace();
					}
				}
			}
			
		});
		thread.start();
	}
	public static void stop()
	{
		if(thread != null)
			thread.interrupt();
	}
	public static void addTrace(String action,User user)
	{
		UserActionTrace trace = new UserActionTrace();
		trace.setAction(action);
		trace.setCompany(user.getCompany());
		trace.setTime(Utils.getCurrentTime());
		trace.setUser(user.getName());
		Request r = new Request();
		UserTraceAddRequestPayload payload = new UserTraceAddRequestPayload(trace);
		r.setPayload(payload);
		r.setAccount(user);
		r.setNeedResponse(false);
		try
		{
			queue.add(r);
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		
	}
}
